import { showLoading, showToast, getCurPage } from 'src/plugins/utils';
import { useStore } from 'src/plugins/pinia';

export default res => {
    return new Promise((resolve, reject) => {
        const httpSuccess = res.data && (Number(res.statusCode) >= 200 && Number(res.statusCode) < 400);
        if (httpSuccess) {
            let rs = {};
            // #ifdef H5
            rs = res.data ? res.data : {};
            // #endif
            // #ifndef H5
            rs = res.data ? JSON.parse(res.data) : {};
            // #endif
            const hshCode = rs.returnCode === 0 || rs.errorCode === 1 ? '200' : '400';
            const hshMsg = rs.returnMsg ? rs.returnMsg : rs.msg ? rs.msg : rs.errMsg;
            rs.code = rs.code ? rs.code : hshCode;
            rs.msg = hshMsg;
            if (rs.code.toString() === '200') {
                resolve(rs);
            } else if (rs.code.toString() === '401') {
                const { user } = useStore();
                user.logout();
                showToast({ 'title': '请求访问令牌非法' });
                setTimeout(() => {
                	const page = getCurPage().route;
                	if (page !== 'pages/login/index') {
                		uni.reLaunch({
                			'url': '/pages/login/index'
                		});
                	}
                }, 1501);
            } else {
                reject(rs.msg);
            }
        } else {
            // uni.showModal(OBJECT);
            showToast({ 'title': '请求失败，请稍后再试' });
            reject(res.data || res.msg);
        }
    });
};